<template>
  <div class="container">
    <el-form :model='searchList' ref='searchList' size='normal'>
      <el-row :gutter='20'>
        <el-col :span='8' :offset='0'>
          <el-form-item label=''>
            <el-input v-model='searchList.name' placeholder="菜单名称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span='8' :offset='0'>
          <el-form-item label=''>
            <el-input v-model='searchList.path' placeholder="菜单链接" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span='8' :offset='0'>
          <div class='right'>
            <el-button type='primary' size='medium' @click='search'>查询</el-button>
            <el-button type="primary" size="medium" @click="handleExpand" :loading="loading">
              <i :class="isExpand?'el-icon-remove-outline':'el-icon-circle-plus-outline'"></i>
              {{isExpand?'关闭全部行':'展开全部行'}}
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <el-table :data='tableData' border stripe :height='offsetHeight' v-loading='loading' ref='table' row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop='name' label='名称' align='left' header-align="center" tree>
      </el-table-column>
      <el-table-column prop='path' label='链接' align='center'>
      </el-table-column>
      <el-table-column prop='type' label='类型' width="100" align='center'>
        <template slot-scope="{row}">
          <el-button type="orange" size="mini" v-if="row.type==='1'">菜单</el-button>
          <el-button type="green" size="mini" v-else>按钮</el-button>
        </template>
      </el-table-column>
      <el-table-column prop='sort' label='排序' width='100' align='center'>
      </el-table-column>
      <el-table-column prop='isShow' label='是否可见' width='120' align='center'>
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" v-if="row.isShow==='1'">可见</el-button>
          <el-button type="danger" size="mini" v-else>不可见</el-button>
        </template>
      </el-table-column>
      <el-table-column label='操作' width='300' align='center'>
        <template slot-scope='{row}'>
          <el-button-group>
            <el-button size="small" type="green" v-if="row.type!=2" @click="addLow(row)">添加下级
            </el-button>
            <el-button size="small" type="primary" @click="update(row)">修改</el-button>
            <el-button size="small" type="danger" @click="remove(row.id)">删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer title="菜单信息" :visible.sync="menuShow" size="70%" center :destroy-on-close="true"
      :wrapperClosable="false">
      <edit-page ref="editPage" :form-params="menuParams" :menu-type="menuType" @cancel="cancel" @init="init">
      </edit-page>
    </el-drawer>
  </div>
</template>

<script>
import EditPage from './edit.vue'
export default {
  name: 'SysMenu',
  components: {
    EditPage
  },
  props: {},
  data () {
    return {
      offsetHeight: document.documentElement.clientHeight - 210,
      loading: false,
      searchList: {},
      tableData: [],
      menuType: [],
      isExpand: false,
      menuShow: false,
      menuParams: {}
    }
  },
  created () {
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      this.loading = true
      const res = await this.$http('sysMenuList', {
        requestType: 'get'
      })
      let menuList = []
      // 添加个根节点，与菜单数组对应,写死的
      let menuList1 = [
        {
          id: "1",
          parent_id: "0",
          value: '1',
          label: '功能菜单',
        },
      ]
      res.forEach(item => {
        // 处理数据
        if (item.parent) {
          item.parent_id = item.parent.id
          item.parent_name = item.parent.name
          item.parent_sort = item.parent.sort
        }
        menuList.push(item)
        // 判断类型是菜单
        if (item.type === '1') {
          menuList1.push({
            id: item.id,
            parent_id: item.parent.id,
            value: item.id,
            label: item.name,
          })
        }
      })
      this.tableData = this.toTree(menuList, 'children', 'id', 'parent_id')
      this.menuType = this.toTree(menuList1, 'children', 'id', 'parent_id')
      this.loading = false
    },
    async search () {
      await this.init()
      if (this.searchList.name || this.searchList.path) {
        this.tableData = this.findTree(this.tableData, this.searchList.name, this.searchList.path)
      }
      this.isExpand = true
      this.handleExpand()
    },
    // 有过有更好的菜单搜索方法，请优化它
    findTree (data, name, path) {
      let result = []
      function getLeaf (data) {
        data.forEach(item => {
          if (name && path) {
            if (item.name.indexOf(name) > -1 && item.path.indexOf(path) > -1) {
              result.push(item)
            } else if (item.children) {
              getLeaf(item.children)
            }
          } else if (name) {
            if (item.name.indexOf(name) > -1) {
              result.push(item)
            } else if (item.children) {
              getLeaf(item.children)
            }
          } else if (path) {
            if (item.path.indexOf(path) > -1) {
              result.push(item)
            } else if (item.children) {
              getLeaf(item.children)
            }
          }
        })
      }
      getLeaf(data)
      // console.log(result);
      return result
    },
    addLow (item) {
      let pid = (item.parent_ids + item.id).replace('0,', '').split(',')
      this.menuParams = {
        parent_ids: pid,
        is_show: item.isShow || '0',
        type: item.type || '1',
      }
      this.menuShow = true
    },
    async update (item) {
      const res = await this.$http('sysMenuObj', {
        id: item.id
      })
      // 分解parent_ids
      let parent_ids = res.parent_ids.replace('0,', '').split(',')
      parent_ids.pop()
      // 父id
      let pid = parent_ids[parent_ids.length - 1]
      this.menuParams = {
        id: res.id,
        pid: pid,
        parent_ids: parent_ids,
        sort: res.sort,
        is_show: item.isShow || '0',
        name: res.name,
        path: res.path,
        permission: res.permission,
        remarks: res.remarks,
        type: res.type
      }
      this.menuShow = true
    },
    async remove (id) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async (action) => {
        const res = await this.$http('sysMenuDel', {
          id: id,
        })
        this.$tips.success(res.errmsg)
        this.init()
      }).catch(() => {

      })
    },
    cancel () {
      this.menuShow = false
    },
    // 菜单遍历重组结构
    toTree (data, children_key, id_key, pid_key) {
      let child_key = children_key || 'children'
      let id = id_key || 'id'
      let pid = pid_key || 'pid'
      // 删除无用子节点
      data.forEach(item => {
        delete item[child_key]
      })
      // 定义map,给map赋值
      let map = {}
      data.forEach(item => {
        map[item[id]] = item
      })
      // 遍历处理
      let arr = []
      data.forEach(item => {
        // 定义父节点，如果有父节点，放入item进入父节点children
        let parent = map[item[pid]]
        if (parent) {
          (parent[child_key] || (parent[child_key] = [])).push(item)
        } else {
          arr.push(item)
        }
      })
      return arr
    },
    // 是否展开table(展开与折叠切换)
    handleExpand () {
      this.isExpand = !this.isExpand
      this.$nextTick(() => {
        this.forArr(this.tableData, this.isExpand)
      })
    },
    // 遍历
    forArr (arr, isExpand) {
      arr.forEach(i => {
        // toggleRowExpansion(i, isExpand)用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        this.$refs.table.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.forArr(i.children, isExpand)
        }
      })
    },

  },
  computed: {
  }
}
</script>
<style lang='scss' scoped>
</style>